package realm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class UsersRealm extends AuthorizingRealm{
	@Override
	public String getName() {
		return "UserRealm";
	}
	
	/**
	 * 验证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username=(String) token.getPrincipal();
		String password = null;
		
		// 通过数据库检查密码是否正确
		String url = "jdbc:mysql://localhost:3306/shiro?useSSL=true" ;     
		String dbUsername = "root" ;    
		String dbPassword = "root" ; 
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection(url, dbUsername, dbPassword);
			PreparedStatement prepareStatement = conn.prepareStatement("select password from users where username=?");
			prepareStatement.setString(1, username);
			ResultSet executeQuery = prepareStatement.executeQuery();
			while(executeQuery.next()) {
				password = executeQuery.getString(1);
				System.out.println(password);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 返回认证信息交给shiro处理
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, password, this.getName());
		return info;
	}
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获得身份信息
		String username = (String) principals.getPrimaryPrincipal();
		
		// 根据身份信息去数据库读取权限信息
		// 这次这里使用模拟数据
		Set<String> permissions = new HashSet<>();
		permissions.add("user:create");
		permissions.add("user:delete");
		
		// 将权限信息保存到AuthorizationInfo交给shiro处理
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 这里如果用的是list的集合也可以使用for循环一个一个的添加
		// 添加方法：addStringPermission
		info.setStringPermissions(permissions);
		return info;
	}

}
